import 'dart:io';
import 'dart:isolate';
import 'error/result.dart';
import 'interpreter/work.dart';

/**
 * 主运行函数多线程调用外部解释器
 */
ReceivePort rp0; //主线程-接收端
SendPort sp0; //主线程-发送端
String fn;
void main(List arg) {
  print("入口参数:${arg.toString()}");
 // if(arg.isEmpty) return;
  if (arg.contains("-cmd")) {
    print("cmd 运行");
    return;
  } else {
    print("文件 运行");
 //   fn=arg[0];
  }
  print("start work main");

  rp0 = new ReceivePort();
  rp0.listen(listenISO);
  Isolate.spawn(doWork, rp0.sendPort);
}

/**
 * 处理线程发过来的消息
 */
void listenISO(result) {
  if (result != null && result is Result) {
    print("[main receive data]:${result.toString()}");
    switch (result.CODE) {
      case 2:
        print(result.MSG);
        break;
      case 0:
        Isolate isolate = result.DATA;
        isolate.kill(priority: Isolate.immediate);
        break;
      case 1: //构建主线程发信通道
        if (result.DATA is SendPort) {
          sp0 = result.DATA;
          String fn = "G:\\language yu\\20210224\\20210101\\test\\test1.yz";
              //"E:\\18.language\\days\\20210101\\test\\test1.yz";
          File f = new File(fn);
          if (f.existsSync()) {
            sp0.send(Result.iso(1, "main file", fn));
          } else {
            print("文件不存在");
          }
        }
        break;
      default:
    }
  } else {
    print("[main receive error]:${result.toString()}");
    if (result.toString() == "exit ok") {
      exit(0); //调用才会退所有线程
    }
  }
}
